﻿using System;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System.IO;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace Bridge.Workflow.Extensions
{
    public static class SwaggerExtensions
    {
        public static IServiceCollection AddSwagger(this IServiceCollection services)
        {
            return services.AddSwaggerGen(options =>
             {
                 var basePath = Path.GetDirectoryName(typeof(WorkflowHttpApiModule).Assembly.Location);
                 var xmlPath = Path.Combine(basePath, "Bridge.Workflow.HttpApi.xml");
                 var xmlPath2 = Path.Combine(basePath, "Bridge.Workflow.Domain.xml");
                 //默认的第二个参数是false,对方法的注释
                 // 即swagger界面只有方法有注释，最上面的控制器没有注释
                 // 而第二个参数为true， 则是controller的注释
                 options.IncludeXmlComments(xmlPath, true);
                 options.IncludeXmlComments(xmlPath2, false);

                 options.SwaggerDoc("v1", new OpenApiInfo()
                 {
                     Title = "Workflow API",
                     Version = "1.0",
                     Description = "工作流管理系统"
                 });

                 options.DocInclusionPredicate((docName, description) => true);
                 //options.IgnoreObsoleteActions();
                 //options.ResolveConflictingActions();

                 // Define the BearerAuth scheme that's in use
                 options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
                 {
                     Description = "请在输入时添加Bearer和一个空格",
                     Name = "Authorization",
                     In = ParameterLocation.Header,
                     Type = SecuritySchemeType.Http,
                     BearerFormat = "JWT"
                 });
             });
        }

        public static void UseSwaggerUI(this IApplicationBuilder app)
        {
            app.UseSwagger();
            //app.UseSwaggerUI(options =>
            //{
            //    options.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkflowService Service API");
            //});

            //app.UseSwaggerUI(options =>
            //{
            //    // specifying the Swagger JSON endpoint.
            //    options.SwaggerEndpoint("/swagger/v1/swagger.json", $"WorkflowService Service API");
            //    options.IndexStream = () => File.OpenRead("wwwroot/swagger/ui/index.html");
            //    options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.  
            //}); // URL: /swagger
        }
    }
}
